
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://app/modules/bbWindowUtils.jsm");

/**
 * BalanceBook Menu system
 */

const addonManagerWindow = "chrome://mozapps/content/extensions/extensions.xul?type=extensions";
const aboutWindow = "chrome://balancebook/content/xul/about.xul";

/**
 * \brief BalanceBook menu operations
 */
var bbMenu = {

  /**
   * Tools Menu Functions
   */
  about: function bbMenu_about() {
    if (!bbWindowUtils.focus("Messenger:About"))
      window.open(aboutWindow, "About",
                  "chrome,resizable=no,minimizable=no,centerscreen");
  },

  preferences: function bbMenu_preferences() {
    if (!bbWindowUtils.focus("Messenger:Preferences"))
      window.open(preferencesWindow, "Preferences",
                  "chrome,titlebar,toolbar,centerscreen,dialog=no");
  },

  addons: function bbMenu_addons() {
    if (!bbWindowUtils.focus("Extension:Manager"))
      window.open(addonManagerWindow, "Addons",
                  "chrome,menubar,extra-chrome,toolbar,dialog=no,resizable");
  },

  open: function bbMenu_open() {
    balancebook.openStorage();
  },

  close: function bbMenu_close() {
    balancebook.closeStorage();
  },
}

/**
 * \brief Main object for controlling the user interface.
 */
var balancebook = {

  /**
   * Private variables
   */

  _obs: null,         // Observer service.

  /**
   * Public Functions
   */

  load: function() {
    this._obs = Cc["@mozilla.org/observer-service;1"]
                  .getService(Ci.nsIObserverService);
  },

  unload: function() {
    bbMenu.close();
    this._obs = null;
  },

  openStorage: function () {
    this.closeStorage();

    var filePicker = Cc["@mozilla.org/filepicker;1"]
                       .createInstance(Ci.nsIFilePicker);
    filePicker.init(window, "Open Database", Ci.nsIFilePicker.modeOpen);
    filePicker.appendFilter("SQLite", "*.sqlite");
    filePicker.appendFilters(Ci.nsIFilePicker.filterAll);
    filePicker.displayDirectory = this._getDocumentFolder();

    var result = filePicker.show();
    if (result == Ci.nsIFilePicker.returnCancel)
      return;

    this._obs.notifyObservers(filePicker.file,
                              "balancebook-storage",
                              "storage-opened");
  },

  closeStorage: function () {
    this._obs.notifyObservers(null,
                              "balancebook-storage",
                              "storage-closed");
  },

  /**
   * Private functions
   */

  _getDocumentFolder: function() {
    // Home : Home folder
    // UsrDocs: OS X Documents folder
    // XDGDocs: Unix Documents folder
    var dirService = Cc["@mozilla.org/file/directory_service;1"]
                       .getService(Ci.nsIProperties);
    return dirService.get("XDGDocs", Ci.nsILocalFile);
  }
}
